<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Token认证测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f7fa;
            min-height: 100vh;
            color: #333;
            font-size: 14px;
            line-height: 1.5;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 15px;
            margin-bottom: 20px;
            text-align: center;
        }

        .section {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .section h2 {
            color: #333;
            margin-bottom: 15px;
            font-size: 18px;
        }

        .status-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #f0f0f0;
        }

        .status-item:last-child {
            border-bottom: none;
        }

        .status-label {
            font-weight: 500;
            color: #666;
        }

        .status-value {
            font-family: monospace;
            font-size: 12px;
            color: #333;
            background: #f8f9fa;
            padding: 4px 8px;
            border-radius: 4px;
        }

        .status-value.true {
            background: #d4edda;
            color: #155724;
        }

        .status-value.false {
            background: #f8d7da;
            color: #721c24;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            margin: 5px;
            transition: all 0.3s ease;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }

        .btn:active {
            transform: scale(0.98);
        }

        .btn-danger {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
        }

        .btn-success {
            background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%);
        }

        .code-block {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            margin: 10px 0;
            font-family: monospace;
            font-size: 12px;
            overflow-x: auto;
            max-height: 200px;
            overflow-y: auto;
        }

        .test-result {
            margin: 10px 0;
            padding: 10px;
            border-radius: 8px;
            font-size: 12px;
        }

        .test-result.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .test-result.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .test-result.info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .nav-links {
            display: flex;
            gap: 10px;
            margin: 20px 0;
            flex-wrap: wrap;
        }

        .nav-links a {
            text-decoration: none;
            color: #667eea;
            font-weight: 500;
            padding: 8px 16px;
            border: 1px solid #667eea;
            border-radius: 6px;
            transition: all 0.3s ease;
        }

        .nav-links a:hover {
            background: #667eea;
            color: white;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔐 Token认证系统测试</h1>
            <p>测试认证状态、Token管理和路由保护功能</p>
        </div>

        <div class="nav-links">
            <a href="home.html">首页</a>
            <a href="index.html">登录页面</a>
            <a href="dashboard.html">控制面板</a>
            <a href="profile.html">个人中心</a>
            <a href="features.html">功能模块</a>
        </div>

        <div class="section">
            <h2>📊 认证状态</h2>
            <div id="authStatus">
                <div class="status-item">
                    <span class="status-label">认证管理器已加载</span>
                    <span class="status-value" id="authManagerLoaded">检查中...</span>
                </div>
                <div class="status-item">
                    <span class="status-label">用户是否已登录</span>
                    <span class="status-value" id="isLoggedIn">检查中...</span>
                </div>
                <div class="status-item">
                    <span class="status-label">Token有效性</span>
                    <span class="status-value" id="tokenValid">检查中...</span>
                </div>
                <div class="status-item">
                    <span class="status-label">Token剩余时间</span>
                    <span class="status-value" id="tokenTimeRemaining">检查中...</span>
                </div>
            </div>
        </div>

        <div class="section">
            <h2>👤 用户信息</h2>
            <div id="userInfo">
                <div class="status-item">
                    <span class="status-label">用户姓名</span>
                    <span class="status-value" id="userName">-</span>
                </div>
                <div class="status-item">
                    <span class="status-label">公司名称</span>
                    <span class="status-value" id="userCompany">-</span>
                </div>
                <div class="status-item">
                    <span class="status-label">微信ID</span>
                    <span class="status-value" id="userMuserid">-</span>
                </div>
                <div class="status-item">
                    <span class="status-label">买家ID</span>
                    <span class="status-value" id="userBuserid">-</span>
                </div>
                <div class="status-item">
                    <span class="status-label">Flag状态</span>
                    <span class="status-value" id="userFlag">-</span>
                </div>
            </div>
        </div>

        <div class="section">
            <h2>🔧 操作测试</h2>
            <div>
                <button class="btn btn-success" onclick="simulateLogin()">模拟登录</button>
                <button class="btn btn-danger" onclick="simulateLogout()">模拟退出</button>
                <button class="btn" onclick="refreshToken()">刷新Token</button>
                <button class="btn" onclick="testApiCall()">测试API调用</button>
                <button class="btn" onclick="clearTestData()">清除测试数据</button>
            </div>
            <div id="testResults"></div>
        </div>

        <div class="section">
            <h2>📋 Token详情</h2>
            <div>
                <button class="btn" onclick="showTokenDetails()">显示Token详情</button>
                <button class="btn" onclick="hideTokenDetails()">隐藏Token详情</button>
            </div>
            <div id="tokenDetails" style="display: none;"></div>
        </div>

        <div class="section">
            <h2>🌐 路由保护测试</h2>
            <div>
                <button class="btn" onclick="testRouteProtection()">测试路由保护</button>
                <button class="btn" onclick="testRedirect()">测试重定向</button>
            </div>
            <div id="routeTestResults"></div>
        </div>
    </div>

    <script src="auth.js"></script>
    <script src="api.js"></script>
    <script src="router.js"></script>
    <script>
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            updateAuthStatus();
            updateUserInfo();
            
            // 监听认证状态变化
            if (window.authManager) {
                window.authManager.onAuthChange('login', function(userData) {
                    addTestResult('用户登录成功', 'success');
                    updateAuthStatus();
                    updateUserInfo();
                });
                
                window.authManager.onAuthChange('logout', function() {
                    addTestResult('用户已退出', 'info');
                    updateAuthStatus();
                    updateUserInfo();
                });
            }
        });

        // 更新认证状态显示
        function updateAuthStatus() {
            const authManagerLoaded = window.authManager ? '是' : '否';
            document.getElementById('authManagerLoaded').textContent = authManagerLoaded;
            document.getElementById('authManagerLoaded').className = 
                'status-value ' + (window.authManager ? 'true' : 'false');

            if (window.authManager) {
                const isLoggedIn = window.authManager.isLoggedIn();
                document.getElementById('isLoggedIn').textContent = isLoggedIn ? '是' : '否';
                document.getElementById('isLoggedIn').className = 'status-value ' + (isLoggedIn ? 'true' : 'false');

                const token = window.authManager.getToken();
                const tokenValid = window.authManager.validateToken(token);
                document.getElementById('tokenValid').textContent = tokenValid ? '有效' : '无效';
                document.getElementById('tokenValid').className = 'status-value ' + (tokenValid ? 'true' : 'false');

                const timeRemaining = window.authManager.getTokenTimeRemaining();
                document.getElementById('tokenTimeRemaining').textContent = timeRemaining + '分钟';
            } else {
                document.getElementById('isLoggedIn').textContent = '否';
                document.getElementById('isLoggedIn').className = 'status-value false';
                document.getElementById('tokenValid').textContent = '无';
                document.getElementById('tokenValid').className = 'status-value false';
                document.getElementById('tokenTimeRemaining').textContent = '无';
            }
        }

        // 更新用户信息显示
        function updateUserInfo() {
            if (window.authManager && window.authManager.isLoggedIn()) {
                const userInfo = window.authManager.getUserInfo();
                document.getElementById('userName').textContent = userInfo.name || '未设置';
                document.getElementById('userCompany').textContent = userInfo.company || '未设置';
                document.getElementById('userMuserid').textContent = userInfo.muserid || '未设置';
                document.getElementById('userBuserid').textContent = userInfo.buserid || '未设置';
                document.getElementById('userFlag').textContent = userInfo.flag || '未设置';
            } else {
                document.getElementById('userName').textContent = '-';
                document.getElementById('userCompany').textContent = '-';
                document.getElementById('userMuserid').textContent = '-';
                document.getElementById('userBuserid').textContent = '-';
                document.getElementById('userFlag').textContent = '-';
            }
        }

        // 模拟登录
        function simulateLogin() {
            if (!window.authManager) {
                addTestResult('认证管理器未加载', 'error');
                return;
            }

            const userData = {
                muserid: 'test_muserid_' + Date.now(),
                buserid: 'test_buserid_' + Date.now(),
                flag: 'Y',
                name: '测试用户',
                company: '测试公司',
                phone: '13800138000'
            };

            window.authManager.setAuth(userData);
            addTestResult('模拟登录成功', 'success');
        }

        // 模拟退出
        function simulateLogout() {
            if (!window.authManager) {
                addTestResult('认证管理器未加载', 'error');
                return;
            }

            window.authManager.clearAuth();
            addTestResult('模拟退出成功', 'info');
        }

        // 刷新Token
        async function refreshToken() {
            if (!window.authManager) {
                addTestResult('认证管理器未加载', 'error');
                return;
            }

            try {
                const success = await window.authManager.refreshToken();
                if (success) {
                    addTestResult('Token刷新成功', 'success');
                    updateAuthStatus();
                } else {
                    addTestResult('Token刷新失败', 'error');
                }
            } catch (error) {
                addTestResult('Token刷新异常: ' + error.message, 'error');
            }
        }

        // 测试API调用
        async function testApiCall() {
            if (!window.apiClient) {
                addTestResult('API客户端未加载', 'error');
                return;
            }

            try {
                // 测试健康检查
                const healthResult = await window.apiClient.healthCheck();
                if (healthResult) {
                    addTestResult('API健康检查通过', 'success');
                } else {
                    addTestResult('API健康检查失败', 'error');
                }
            } catch (error) {
                addTestResult('API调用失败: ' + error.message, 'error');
            }
        }

        // 清除测试数据
        function clearTestData() {
            if (window.authManager) {
                window.authManager.clearAuth();
            }
            
            // 清除localStorage中的所有认证相关数据
            const keysToRemove = [
                'wechat_auth_token',
                'wechat_user_info',
                'wechat_token_expiry',
                'wechat_refresh_token',
                'userData'
            ];
            
            keysToRemove.forEach(key => {
                localStorage.removeItem(key);
            });
            
            addTestResult('测试数据已清除', 'info');
            updateAuthStatus();
            updateUserInfo();
        }

        // 显示Token详情
        function showTokenDetails() {
            if (!window.authManager) {
                addTestResult('认证管理器未加载', 'error');
                return;
            }

            const token = window.authManager.getToken();
            if (!token) {
                addTestResult('没有Token可显示', 'error');
                return;
            }

            const decoded = window.authManager.decodeToken(token);
            const details = document.getElementById('tokenDetails');
            
            details.innerHTML = `
                <div class="code-block">
                    <strong>原始Token:</strong><br>
                    ${token}<br><br>
                    <strong>解码后的Payload:</strong><br>
                    ${JSON.stringify(decoded, null, 2)}
                </div>
            `;
            
            details.style.display = 'block';
            addTestResult('Token详情已显示', 'success');
        }

        // 隐藏Token详情
        function hideTokenDetails() {
            document.getElementById('tokenDetails').style.display = 'none';
            addTestResult('Token详情已隐藏', 'info');
        }

        // 测试路由保护
        function testRouteProtection() {
            if (!window.routeGuard) {
                addTestResult('路由保护未加载', 'error');
                return;
            }

            const routeInfo = window.routeGuard.getCurrentRouteInfo();
            addTestResult('当前路由信息: ' + JSON.stringify(routeInfo, null, 2), 'info');
        }

        // 测试重定向
        function testRedirect() {
            const currentUrl = encodeURIComponent(window.location.href);
            const loginUrl = `index.html?redirect=${currentUrl}`;
            
            addTestResult('准备重定向到登录页面: ' + loginUrl, 'info');
            
            if (confirm('确定要跳转到登录页面吗？')) {
                window.location.href = loginUrl;
            }
        }

        // 添加测试结果
        function addTestResult(message, type) {
            const resultsDiv = document.getElementById('testResults');
            const resultDiv = document.createElement('div');
            resultDiv.className = 'test-result ' + type;
            resultDiv.textContent = '[' + new Date().toLocaleTimeString() + '] ' + message;
            
            resultsDiv.insertBefore(resultDiv, resultsDiv.firstChild);
            
            // 限制显示的测试结果数量
            const results = resultsDiv.querySelectorAll('.test-result');
            if (results.length > 10) {
                results[results.length - 1].remove();
            }
        }

        // 自动刷新状态
        setInterval(updateAuthStatus, 30000); // 每30秒刷新一次
    </script>
</body>
</html>